package com.htfyun.factorytest.engineerui;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.ref.WeakReference;

import androidx.core.app.ActivityCompat;

import com.htfyun.factorytest.config.HtfyunBuildConfig;

import com.htfyun.factorytest.R;

import com.htfyun.factorytest.utils.DebugLog;


public class WifiActivity extends Activity {


    private Context mContext;
    private TextView txtSsidInfo;
    private Button btnFail;

    private MyHandler mHandler;

    private boolean isPcba;


    private static final class MyHandler extends Handler {
        private final static int MSG_UPDATE_SSID = 100;
        private final static int PERIOD_UPDATE_SSID = 3000;

        private WeakReference<WifiActivity> reference;

        public MyHandler(WifiActivity activity) {
            reference = new WeakReference<WifiActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            WifiActivity wifiActivity = reference.get();
            if (wifiActivity == null) {
                return;
            }
            if (msg.what == MSG_UPDATE_SSID) {
                wifiActivity.handleUpdateSsid();
            }

        }
    }


    private void handleUpdateSsid() {
        WifiManager wifiManager = (WifiManager) mContext.getSystemService(WifiManager.class);
        if (wifiManager != null) {
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            if (wifiInfo != null && wifiInfo.getBSSID() != null) {
//                int strenth = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), 5);
                String ssid = wifiInfo.getSSID();
                int rssi = wifiInfo.getRssi();
                txtSsidInfo.setText(getResources().getString(R.string.wifi_ssid, ssid, rssi));

                if (rssi >= HtfyunBuildConfig.WIFI_MIN_RSSI) {
                    finishWithOK();
                }
            }

            mHandler.sendEmptyMessageDelayed(MyHandler.MSG_UPDATE_SSID, MyHandler.PERIOD_UPDATE_SSID);
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.activity_wifi);

        TextView txtInfo = (TextView) findViewById(R.id.txtInfo);
        txtInfo.setText(getString(R.string.wifi_test_info, HtfyunBuildConfig.WIFI_MIN_RSSI));

        isPcba = getIntent().getBooleanExtra("isPcba", false);

        mHandler = new MyHandler(this);

        txtSsidInfo = (TextView) findViewById(R.id.txtSsidInfo);
        findViewById(R.id.btnFail).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishWithFail();
            }
        });

        findViewById(R.id.btnJumpToSelectWifi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startWifiSettings();
            }
        });

        mContext = this;

        if (isPcba) {

            startWifiSettings();

        } else {

            if (!isWifiEnabled(mContext) || !isWifiConnected(mContext)) {
                startWifiSettings();
            }
        }

    }

    private void finishWithOK() {
        Toast.makeText(mContext, R.string.test_ok, Toast.LENGTH_SHORT).show();
        setResult(RESULT_OK);
        ActivityCompat.finishAfterTransition(WifiActivity.this);
    }

    private void finishWithFail() {
        Toast.makeText(mContext, R.string.test_fail, Toast.LENGTH_SHORT).show();
        setResult(RESULT_CANCELED);
        ActivityCompat.finishAfterTransition(WifiActivity.this);
    }

    private void startWifiSettings() {

        if (startAndroidWifiSettings()) {
            return;
        }

        if (startIflytekWifiSettings()) {
            return;
        }

        Toast.makeText(mContext, R.string.wifi_no_settings, Toast.LENGTH_LONG).show();

    }
    private boolean startAndroidWifiSettings() {
        try {

            Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
            startActivity(intent);

        } catch (Exception e) {

            return false;
        }

        return true;
    }
    private boolean startIflytekWifiSettings() {

        try {

            Intent intent = new Intent(Intent.ACTION_MAIN);
            ComponentName cn = new ComponentName("com.iflytek.ainote.launcher", "com.iflytek.ainote.ui.activity.CommonWifiSettingActivity");
            intent.setComponent(cn);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

        } catch (Exception e) {

            return false;
        }

        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerWifiReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterWifiReceiver();
        mHandler.removeMessages(MyHandler.MSG_UPDATE_SSID);

    }

    public  boolean isWifiEnabled(Context context) {
        WifiManager wm = (WifiManager) context
                .getSystemService(WifiManager.class);

        return (wm != null && wm.isWifiEnabled());
    }

    public  boolean isWifiConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
            return false;
        }
        NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (info != null && info.isConnected()) {
            DebugLog.i( "Wifi网络连接成功");
            return true;
        }
        DebugLog.i( "Wifi网络连接失败");
        return false;
    }


    private void registerWifiReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        registerReceiver(wifiStateChangedReceiver, filter);
    }

    private void unregisterWifiReceiver() {
        unregisterReceiver(wifiStateChangedReceiver);
    }


    private BroadcastReceiver wifiStateChangedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action == null) {
                return;
            }
            DebugLog.i( "actioin:" + action);

            if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {//这个监听wifi的打开与关闭，与wifi的连接无关
                int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, -1);
                DebugLog.d( "wifiState:" + wifiState);
                switch (wifiState) {
                    case WifiManager.WIFI_STATE_DISABLED:
                        DebugLog.d( "wifiState:WIFI_STATE_DISABLED");
                        break;
                    case WifiManager.WIFI_STATE_DISABLING:
                        DebugLog.d( "wifiState:WIFI_STATE_DISABLING");
                        break;
                    case WifiManager.WIFI_STATE_ENABLED:
                        DebugLog.d( "wifiState:WIFI_STATE_ENABLED");
                        break;
                    case WifiManager.WIFI_STATE_ENABLING:
                        DebugLog.d( "wifiState:WIFI_STATE_ENABLING");
                        break;
                    case WifiManager.WIFI_STATE_UNKNOWN:
                        DebugLog.d( "wifiState:WIFI_STATE_UNKNOWN");
                        break;
                    //
                }
            }
            // 这个监听wifi的连接状态即是否连上了一个有效无线路由，当上边广播的状态是WifiManager.WIFI_STATE_DISABLING，和WIFI_STATE_DISABLED的时候，根本不会接到这个广播。
            // 在上边广播接到广播是WifiManager.WIFI_STATE_ENABLED状态的同时也会接到这个广播，当然刚打开wifi肯定还没有连接到有效的无线
            if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
                Parcelable parcelableExtra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO);
                String bssid = intent.getStringExtra(WifiManager.EXTRA_BSSID);

                if (null != parcelableExtra) {
                    NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;
                    NetworkInfo.State state = networkInfo.getState();
                    DebugLog.d( "NetWork Sate Change:" + state);

                    if (state == NetworkInfo.State.DISCONNECTED) {

                        DebugLog.d( "wifi disconnected ");
                        txtSsidInfo.setText(getResources().getString(R.string.wifi_disconected));
                        mHandler.removeMessages(MyHandler.MSG_UPDATE_SSID);

                    } else if (state == NetworkInfo.State.CONNECTED) {

                        mHandler.sendEmptyMessage(MyHandler.MSG_UPDATE_SSID);
                    }
                }
            }
        }
    };


}
